﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using GL.Tools;


namespace WAD.WEB.Client2
{
    /// <summary>
    /// 跳转到文章预览界面
    /// </summary>
    public partial class to_detail : WebBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int type = Parse.Int("type", 0);
            int is_app = Parse.Int("is_app", 0);
            int user_id = Parse.Int("user_id", 0);
            //外部链接分享
            if (type == 2)
            {
                ToUrlDetail();
                return;
            }

            int articleId = Parse.Int("article_id", 0);//文章id跳转
            int sharedId = Parse.Int("shared_id", 0);//分享id跳转

            MShared m = null;
            if (articleId != 0)
            {
                //根据一篇文章的id 去获取作者的分享信息
                m = DaoShared.GetAuthorShared(articleId, user_id);
                if (m == null)
                {
                    Redirect("detail.aspx?is_app=1&article_id=" + articleId);
                }
            }
            else if (sharedId != 0)
            {
                m = DaoShared.GetInfo(sharedId);
                if (m == null)
                {
                    Redirect("Index.html?4");
                }
            }
            else
            {
                Redirect("Index.html?1");
            }

            String redir = "";
            redir = "detail.aspx?is_app=1&shareid=" + m.id + "&advert_id=" + m.advert_id;

            //分享类型
            if (m.type == 1)
            {
                redir += "&article_id=" + m.article_id;
            }
            else
            {
                redir += "&url=" + Server.UrlEncode(m.url) + "&type=" + m.type + "&url_title=" + m.url_title;
            }

            Redirect(redir);
        }

        /// <summary>
        /// 跳转到外部链接访问
        /// </summary>
        private void ToUrlDetail()
        {
            String url = Parse.String("url");//外部链接地址
            String title = Parse.String("title");
            String logo = Parse.String("logo");

            if (logo.IndexOf("//mmbiz.qpic.cn") != -1)
            {
                string savaPath;    //格式：磁盘/Upload/Image/2015/02/28/20160301141712B4FyjS.jpg
                if (!string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                    savaPath = string.Format("{0}{1}{2}/{3}/{4}{5}{6}", WJXConfig.Path.UPLOAD_DIR, WJXConfig.Path.IMAGE, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyyMMddHHmmss"), StringHelper.Random(6), ".jpg");
                else
                    savaPath = string.Format("{0}{1}/{2}/{3}{4}{5}", HttpContext.Current.Server.MapPath(WJXConfig.Path.IMAGE), DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyyMMddHHmmss"), StringHelper.Random(6), ".jpg");

                //微信图片下载到本地
                if (HttpTool.SavaFile(logo, savaPath))
                {
                    if (!string.IsNullOrEmpty(WJXConfig.Path.UPLOAD_DIR))
                        logo = savaPath.Substring(savaPath.IndexOf(WJXConfig.Path.UPLOAD_DIR) + WJXConfig.Path.UPLOAD_DIR.Length);
                    else
                        logo = savaPath.Substring(savaPath.IndexOf(Server.MapPath(WJXConfig.Path.IMAGE)) + WJXConfig.Path.IMAGE.Length);
                }
            }

            //微街秀链接处理 06-14
            //url = FormatUrl(url);   

            Redirect("detail_url.html?is_app=1&type=2&url=" + Server.UrlEncode(url) + "&title=" + Server.UrlEncode(title) + "&logo=" + Server.UrlEncode(logo));
        }

        string FormatUrl(string url)
        {
            if (url.IndexOf("item.aspx") > -1 || url.IndexOf("item_new.aspx") > -1)
            {
                Regex r1 = new Regex("&shareid=([\\s\\S].*?)&");
                Regex r2 = new Regex("article_id=([\\s\\S].*?)&");
                Regex r3 = new Regex("&shareid=([\\s\\S].*?)$");


                string v1 = r1.Match(url).Groups[1].Value;
                string v2 = r2.Match(url).Groups[1].Value;

                if (v2.Length > 0 && (!v2.Equals("0")))
                {
                    //原创
                    if (url.IndexOf("?") > -1)
                        url = WJXConfig.Path.Shared_Domain + "/item_article.aspx?" + url.Substring(url.IndexOf("?") + 1);
                    else
                        url = WJXConfig.Path.Shared_Domain + "/item_article.aspx?article_id" + v2;
                }
                else
                {
                    if (string.IsNullOrEmpty(v1))
                        v1 = r3.Match(url).Groups[1].Value;

                    if (!string.IsNullOrEmpty(v1))
                    {
                        //外链
                        try
                        {
                            MShared m = DaoShared.GetInfo(Convert.ToInt32(v1));
                            if (m != null && (!string.IsNullOrEmpty(m.url)))
                                url = m.url;
                        }
                        catch { }
                    }
                }
            }
            return url;
        }

        /// <summary>
        /// 跳转到外部链接访问
        /// </summary>
        //private void ToUrlDetail2()
        //{
        //    //http://mp.weixin.qq.com/s?__biz=MzAwODA1ODk0Ng==&mid=400777038&idx=1&sn=1e07419a8e157e74c8c7cfda340c4367&scene=1&srcid=1114D0V6IcgavwIBAjXqf49u&from=singlemessage&isappinstalled=0#wechat_redirect
        //    //公众号网址，需要去掉后面#wechat_redirect ,防止框架内URL自动跳转

        //    String url = Parse.String("url", "");//外部链接地址
        //    if (url.IndexOf("mp.weixin.qq.com") > -1)
        //        url = url.Replace("#wechat_redirect", "");
        //    String title = "";
        //    string urlimg = "";

        //    try
        //    {
        //        //如果是微信订阅号的链接,将源码保存至数据库
        //        if (url.IndexOf("mp.weixin.qq.com") > -1)
        //        {
        //            int sourceId = 0;
        //            String md5 = StringHelper.MD5Encrypt(url);
        //            Dictionary<String, object> map = DaoUrlSource.GetEntityByMd5(md5);

        //            if (map != null)
        //            {
        //                title = map["title"].ToString();
        //                urlimg = map["urlimg"].ToString();
        //                sourceId = (int)map["id"];
        //            }
        //            else
        //            {
        //                String htmlStr = HttpTool.GetHttpString(url, true);
        //                title = HttpTool.GetHtmlTitle(htmlStr);//获取该链接的title标签内容
        //                urlimg = HttpTool.GetHtmlImg(htmlStr);

        //                //htmlStr = FormatHtml(htmlStr);

        //                Regex r1 = new Regex("id=\"media\">([\\s\\S]+)<div class=\"rich_media_content \" id=\"js_content\">");
        //                if (r1.IsMatch(htmlStr))
        //                {
        //                    Regex r2 = new Regex("var cover = \"([\\s\\S]+)\";");
        //                    string temp = r1.Match(htmlStr).Groups[1].Value;
        //                    //替换图片
        //                    if (r2.IsMatch(temp))
        //                        htmlStr = htmlStr.Replace(temp, string.Format("<script>showImg('{0}');</script></div>", r2.Match(temp).Groups[1].Value));
        //                }

        //                MUrlSource m = new MUrlSource() { md5 = md5, source = HttpTool.FormatImg(htmlStr.Replace("</head>", "<script src=\"/Client/js/format_img.js\" type=\"text/javascript\"></script></head>")), title = title, urlimg = urlimg, url = url };
        //                sourceId = DaoUrlSource.Add(m);
        //                if (sourceId == 0)
        //                {
        //                    Redirect("index.html?2");
        //                }
        //            }

        //            url = "weixin.aspx?source_id=" + sourceId;
        //        }
        //        else
        //        {
        //            String htmlStr = HttpTool.GetHttpString(url, true);
        //            title = HttpTool.GetHtmlTitle(htmlStr);//获取该链接的title标签内容
        //            urlimg = HttpTool.GetHtmlImg(htmlStr);
        //        }
        //    }
        //    catch
        //    {
        //        Redirect("index.html?3");
        //    }

        //    Redirect("detail_url.html?is_app=1&type=2&url=" + Server.UrlEncode(url) + "&url_title=" + title + "&urlimg=" + Server.UrlEncode(urlimg));
        //}

    }
}